<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/7/2
 * Time: 9:26
 */

namespace common\models\Service;


use common\models\CommonFunction;
use common\models\DAO\Invest;
use common\models\DAO\InvestInfo;
use common\models\DAO\InvestList;
use common\models\DAO\User;
use common\models\DAO\UserCoupon;
use common\models\DAO\UserCouponUseList;
use common\models\DAO\UserHongbao;
use common\models\DAO\UserHongbaoUseList;
use common\models\DAO\UserInvest;
use common\msg\UserMsg;

class DetailService {
	
	//用户资产详情
	public static function userAssets($userID)
	{
		//账户余额
		$user['remainder'] = sprintf("%.2f",Wallet::remainder($userID)/100);
		$user['hongbao'] = sprintf("%.2f",HongBaoService::get($userID)/100);
		//获取第一个coupon
		$user['coupon]']=CouponService::getListwei($userID,1,1);
		return $user;
	}
	
    public static function init($id, $userID = 0){
        $result = [];
        //标的基础信息
        $investInfo = Invest::findOne($id);
        if(!$investInfo)
            return false;
        $status = $investInfo['status'];
        $now = time();
        if($status == 0 || $status == 4 || $investInfo['beginTime'] > $now/* || $now >= $investInfo['endTime']*/)
            return false;
        $inveset_content = InvestInfo::findOne($id);
        $content = '';
        if($inveset_content)
            $content = $inveset_content['content'];
        $info['content'] = $content;
        $info['comInfo'] = $inveset_content['comInfo'];
        $info['name'] = $investInfo['investName'];
        $info['fristTime'] = date('Y-m-d H:i',$inveset_content['firstTime']);
        $info['lastTime'] = date('Y-m-d H:i',$inveset_content['lastTime']);
        $info['createTime'] = date('Y-m-d H:i',$investInfo['createTime']);
        $info['remainderTime'] = intval($investInfo['endTime']) - time() < 0 ? 0 :intval($investInfo['endTime']) - time();
        $info['investDate'] = $investInfo['investDate'];
        $info['person'] = $investInfo['person'];
        $info['status'] = $investInfo['status'];
        $info['remainderMoney'] = CommonFunction::formatMoney(intval($investInfo['money']) - intval($investInfo['progress']));
        $info['money'] = CommonFunction::formatWan($investInfo['money']);
        $info['rate'] = CommonFunction::formatMoney($investInfo['rate']);
        $info['progress'] = floor(intval($investInfo['progress'])/intval($investInfo['money'])*10000)/100;
        $result['invest_surplus'] = (intval($investInfo['money']) - intval($investInfo['progress']))/100;
        $result['least_invest'] = \Yii::$app->params['least_invest'] / 100;
        //认证信息
        $auth = [];
        if($inveset_content['authIDs']){
            $auth = explode(',', $inveset_content['authIDs']);
        }
        $result['auth'] = $auth;

         /*$invest_user = $investInfo['userID'];

         //逾期次数，金额
         $overdue = OverdueService::get($invest_user);
         $info['overMoney'] = CommonFunction::formatWan($overdue['overMoney']);
         $info['overAmount'] = $overdue['overAmount'];

         //借款次数
         $info['loanAmount'] = LoanService::userLoanTime($invest_user);

         //成功借款次数
         $loan_success = InvestService::userSuccessTime($invest_user);
         $info['successAmount'] = $loan_success['amount'];
         $info['successMoney'] = CommonFunction::formatWan($loan_success['money']);


         //还清次数
         $info['successCount'] = InvestService::userRepaymentTime($invest_user);*/
        $user_remainder = 0;
        $user_hongbao = 0;
        $hb_scale = 0;
        if(!empty($userID)){
            $result['list'] = self::getList($id);
            $result['count'] = InvestList::find()->where(['investID'=>$id])->count();
            $user['remainder'] = CommonFunction::formatMoney(Wallet::remainder($userID));
            $user['hongbao'] = CommonFunction::formatMoney(HongBaoService::get($userID));
            $result['user'] = $user;
            $user_remainder = Wallet::remainder($userID) / 100;
            $user_hongbao = HongBaoService::get($userID) / 100;
            $hb_scale= HongBaoService::setting($investInfo['investDate']);
        }
        $result['hb_scale'] = $hb_scale;
        $result['user_remainder'] = $user_remainder;
        $result['user_hongbao'] = $user_hongbao;
        $result['info'] = $info;
        return $result;
    }

    /*
       *获取标投资列表
       */
    public static function getList($investID, $page = 1, $limit = 10){
        $start = ($page - 1) * $limit;
        $list = InvestList::find()->where(['investID'=>$investID])->with('user')->limit($limit)
            ->offset($start)->orderBy('id asc')->asArray()->all();
        $result = array();
        if($list){
            foreach($list as $v){
                $_list = [];
                $phone = CommonFunction::decrypt(($v['user']['phone']));
                $_list['phone'] = CommonFunction::dealTel($phone);
                $_list['time'] = date('Y-m-d H:i:s',$v['createTime']);
                $_list['money'] = CommonFunction::formatWan($v['money']);
                $result[] = $_list;
            }
        }
        return $result;
    }

    /*
     * 投标动作
     */
    public static function complete($param, $sourceID = 1){
        $result['status'] = 0;
        $result['msg'] = UserMsg::$time_out;
        if(!isset($param['id']))
            return $result;
        //标的基础信息
        $investInfo = Invest::findOne($param['id']);
        if(!$investInfo)
            return $result;
        $status = $investInfo['status'];
        $investID = $param['id'];
        $now = time();
        if($status == 0 || $status == 4 || $investInfo['beginTime'] > $now/* || $now >= $investInfo['endTime']*/){
            $result['msg'] = UserMsg::$invest_lose;
            return $result;
        }
        if($investInfo['progress'] >= $investInfo['money']){
            $result['msg'] = UserMsg::$invest_full;
            return $result;
        }
        $userID = $param['userID'];
        $remainder = Wallet::remainder($userID);
        $money = intval(floatval($param['money']) * 100);
        $coupon = 0;
        $hongbao = 0;
        $day = $investInfo['investDate'];
        $least_invest = \Yii::$app->params['least_invest'];
        if($money < intval($least_invest)){
            $result['msg'] = '投资金额不能少于'.$least_invest/100 . '元!';
            return $result;
        }

        if($investInfo['progress'] + $money > $investInfo['money']){
            $result['msg'] = '最多可投'.CommonFunction::formatMoney($investInfo['money'] - $investInfo['progress']).'元!';
            return $result;
        }
        if($money > $remainder ){
            $result['msg'] = UserMsg::$no_money;
            return $result;
        }
        if(isset($param['hongbao'])){
            $hb_scale = HongBaoService::setting($day);

            $hongbao = floatval($param['hongbao']) * 100;

            $can_use_hongbao = $money / $hb_scale;
            if($can_use_hongbao < $hongbao){
                $result['msg'] = '本次投资，现金红包最大可使用' . CommonFunction::formatWan($can_use_hongbao) . '元。';
                return $result;
            }
            $user_hongbao = 0;
            $user_hongbao_model = UserHongbao::findOne($userID);
            $user_hongbao_model && $user_hongbao = $user_hongbao_model['money'];
            if($hongbao > $user_hongbao){
                $result['msg'] = UserMsg::$no_hongbao;
                return $result;
            }
        }
        $couponID = 0;
        if(isset($param['couponID'])){
            $couponID = intval($param['couponID']);
            $coupon_model = UserCoupon::findOne(['id'=>$couponID, 'userID'=>$userID, 'status'=>0]);
            if(!$coupon_model || date('Ymd') >= $coupon_model['loseTime']){
                $result['msg'] = UserMsg::$no_coupon;
                return $result;
            }
            $coupon = $coupon_model['card'];
        }
        $transaction = \Yii::$app->db->beginTransaction();


        //更新用户投资列表
        $rate = $investInfo['rate'];
        $start_date =  date("Ymd",strtotime("+1 day"));
        $over_day = $day + 1;
        $end_date =  date("Ymd",strtotime("+$over_day day"));
        $system_day = \Yii::$app->params['system_day'];
        $accrual = intval(($money + $hongbao) * ($rate + $coupon) * $day / $system_day / 10000);
        $userInvest = new UserInvest();
        $userInvest->userID = $userID;
        $userInvest->investID = $investID;
        $userInvest->title = $investInfo['investName'];
        $userInvest->startTime = $start_date;
        $userInvest->endTime = $end_date;
        $userInvest->money = $money + $hongbao;
        $userInvest->accrual = $accrual;
        $userInvest->typeID = 0;
        $userInvest->createTime = $now;
        $userInvest->sourceID = $sourceID;
        $userInvest->rate = $rate + $coupon;
        $userInvest->hongBao = $hongbao;
        $userInvest->couponID = $couponID;
        $userInvest->coupon = $coupon;

        $userInvest_result = $userInvest->save();
        if(!$userInvest_result){
            $transaction->rollBack();
            return $result;
        }

        $userInvestID = $userInvest->id;

        //公共参数
        $pub_param['userID'] = $userID;
        $pub_param['investID'] = $investID;

        //更新用户余额 - 扣除账户余额
        $accrual_param = $pub_param;
        $accrual_param['userInvestID'] = $userInvestID;
        $accrual_param['money'] = $money;
        $accrual_param['createTime'] = $now;
        $accrual_param['productID'] = 0;
        $accrual_param['wallet_type'] = 2;
        $accrual_param['wallet_road'] = 3;
        $accrual_result = Wallet::deduct($accrual_param, 'desc');
        if(!$accrual_result){
            $transaction->rollBack();
            return $result;
        }
        //分销系统
        if(isset($param['recID'])){
            $team_patam['tel'] = $param['tel'];
            $team_patam['userID'] = $userID;
            $team_patam['money'] = $money + $hongbao;
            $team_patam['day'] = $day;
            $team_patam['recID'] = $param['recID'];
            $team_patam['investID'] = $investID;
            $team_patam['productID'] = 0;
            $team_patam['userInvestID'] = $userInvestID;
            $team_result = TeamService::insert($team_patam);
            if(!$team_result){
                $transaction->rollBack();
                return $result;
            }
        }
        //投资记录
        $invest_list_param = $pub_param;
        $invest_list_param['title'] = $investInfo['investName'];
        $invest_list_param['startTime'] = $start_date;
        $invest_list_param['endTime'] = $end_date;
        $invest_list_param['createTime'] = $now;
        $invest_list_param['rate'] =  $rate + $coupon;
        $invest_list_param['money'] = $money + $hongbao;
        $invest_list_param['accrual'] = $accrual;
        $invest_list_param['hongbao'] = $hongbao;
        $invest_list_param['couponID'] = $couponID;
        $invest_list_param['coupon'] = $coupon;
        $invest_list_param['sourceID'] = $sourceID;
        $investList_result = InvestListService::add($invest_list_param);
        if(!$investList_result){
            $transaction->rollBack();
            return $result;
        }

        //更新红包状态
        if($hongbao > 0 && isset($user_hongbao_model) && !empty($user_hongbao)){
            $user_hongbao_model->money = $user_hongbao - $hongbao;
            $hb_result = $user_hongbao_model->save();
            if(!$hb_result){
                $transaction->rollBack();
                return $result;
            }
            $hb_use = new UserHongbaoUseList();
            $hb_use->userID = $userID;
            $hb_use->hongBao = $hongbao;
            $hb_use->createTime = $now;
            $hb_use->userInvestID = $userInvestID;
            $hb_use->investID = $investID;
            $hb_use->type = 0;
            $hb_use_result = $hb_use->save();
            if(!$hb_use_result){
                $transaction->rollBack();
                return $result;
            }

        }
        //更新年利卷状态
        if($couponID > 0 && $coupon > 0 && isset($coupon_model)){
            $coupon_model->status = 1;
            $coupon_result = $coupon_model->save();
            if(!$coupon_result){
                $transaction->rollBack();
                return $result;
            }
            $coupon_use_model = new UserCouponUseList();
            $coupon_use_model->userID = $userID;
            $coupon_use_model->useTime = $now;
            $coupon_use_model->card = $coupon;
            $coupon_use_model->userInvestID = $userInvestID;
            $coupon_use_model->investID = $investID;
            $coupon_use_model->couponID = $couponID;
            $coupon_use_result = $coupon_use_model->save();
            if(!$coupon_use_result){
                $transaction->rollBack();
                return $result;
            }
        }

        //用户日志
        $user_log = UserLog::set(['userID'=>$userID, 'money'=> $money + $hongbao, 'hongBao'=> $hongbao, 'rate'=>$rate + $coupon, 'coupon'=>$coupon,
            'investID'=>$investID, 'sourceID'=>$sourceID, 'desc'=>'投资'.$investInfo['investName']]);
        if(!$user_log){
            $transaction->rollBack();
            return $result;
        }

        $user_integral_param = $pub_param;
        $user_integral_param['userInvestID'] = $userInvestID;
        $user_integral_param['day'] = $day;
        $user_integral_param['money'] = $money + $hongbao;
        $user_integral_param['createTime'] = $now;
        $user_integral_param['desc'] = '投资【'.$investInfo['investName'].'】';
        $user_integral_param['productID'] = 0;
        $user_integral_result = IntegralService::add($user_integral_param);
        if(!$user_integral_result){
            $transaction->rollBack();
            return $result;
        }
        $invest_progress = intval($investInfo['progress']);
        $investInfo->progress = $invest_progress + $money + $hongbao;
        $investInfo->person = $investInfo['person'] + 1;
        if($invest_progress + $money >= $investInfo['money']){
            $investInfo->status = 2;
            $investInfo->fullTime = $now;
        }
        $invset_result = $investInfo->save();
        if(!$invset_result){
            $transaction->rollBack();
            return $result;
        }else{
            $transaction->commit();
            if(!empty($param['openID'])){
                $send_param = ['openID'=>$param['openID'],'name'=>$investInfo['investName'],
                               'rate'=> CommonFunction::formatMoney($rate + $coupon).'%',
                                'day'=>$day.'天',
                                'money'=>CommonFunction::formatMoney($money + $hongbao).'元',
                                'accrual'=>CommonFunction::formatMoney($accrual).'元',
                                'id'=>$userInvestID
                ];
                SendWxMessage::invest($send_param);
            }
        }

        return ['status'=>1,'id'=>$userInvestID, 'url'=> \Yii::$app->urlManager->createUrl(['invest/index', 'id' => $userInvestID])];
    }
}